package middleware

import (
	"context"
	"errors"
	"mpps/tools/auth"
	"mpps/tools/common"
	"mpps/tools/config"
	"regexp"
	"strings"

	"github.com/asim/go-micro/v3/logger"
	"github.com/asim/go-micro/v3/metadata"
	"github.com/asim/go-micro/v3/server"
)

func SrvAuthMiddleware(handlerFunc server.HandlerFunc) server.HandlerFunc {
	return func(ctx context.Context, req server.Request, rsp interface{}) error {
		logger.Info("server request: ", req.Service(), " "+req.Endpoint())
		// 不需要验证
		pattern := strings.Join(config.SrvTokenFilter, "|")
		if ok, _ := regexp.MatchString(pattern, req.Endpoint()); ok {
			return handlerFunc(ctx, req, rsp)
		}
		// 需要验证
		md, ok := metadata.FromContext(ctx)
		if !ok {
			logger.Info(common.ErrAuth)
			return errors.New(common.ErrAuth.Message)
		}
		// 首字母会变成大写
		token := md["Token"]
		// 如果没有值，检查是否被过滤或者检查context是否包装token--auth.WithToken(c)。
		// 例如：m.UserRefreshTokenService.Call(auth.WithToken(c), ...)
		logger.Infof("token=%v", token)
		// 校验
		if claims, err := auth.ParseToken(token, false); err == nil {
			logger.Infof("claims=%v", claims)
			return handlerFunc(ctx, req, rsp)
		} else {
			logger.Info(common.ErrAuth, err)
			return errors.New(common.ErrAuth.Message)
		}
	}
}
